package io.sage.modules.socket.service.impl;

import io.sage.modules.socket.service.SocketServerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Mafy on 2019/7/15.
 */
@Service("socketServerService")
public class SocketServerServiceImpl extends Thread implements SocketServerService {
    ServerSocket server = null;
    Socket socket = null;

    @Value(value="${socket.localPort}")
    private int port;

    @Override
    public void run(){
        try{
            System.out.println("wait client connect...");
            if(ObjectUtils.isEmpty(server)){
                server = new ServerSocket(port);
            }

            socket = server.accept();
            System.out.println(socket.getInetAddress().getHostAddress()+"SUCCESS TO CONNECT...");
            InputStream in = socket.getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len=in.read(buf))!=-1){
                //todo 处理客户端过来的数据
                System.out.println("client saying: "+new String(buf,0,len));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
